package com.ziwei.material.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.ziwei.material.domain.dto.ExcelData;
import com.ziwei.material.domain.po.SdsMaterialTaskPic;
import com.ziwei.material.manage.MaterialTaskImportManager;
import com.ziwei.material.service.MaterialTaskDownloadService;
import com.ziwei.material.service.MaterialTaskImportService;
import com.ziwei.material.service.MaterialTaskService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: jl_zhang
 * @since: 2024/11/15 10:15
 **/
//excel数据导入-第一步-导入
@Service
@RequiredArgsConstructor
public class MaterialTaskImportServiceImpl  implements MaterialTaskImportService {

    private final MaterialTaskService materialTaskService;

    private final MaterialTaskImportManager materialTaskImportManager;

    private final MaterialTaskDownloadService materialTaskDownloadService;




    //异步执行导入任务
    @Async
    @Override
    public void importExecute(MultipartFile excel, Long userId, Long taskId) {
        List<SdsMaterialTaskPic> list = new ArrayList<>();
        try{
            //获取文件的输入流
            InputStream in = excel.getInputStream();

            //读取Excel文件, 映射到ExcelData类
            EasyExcel.read(in, ExcelData.class, new ReadListener<ExcelData>() {
                @Override
                public void invoke(ExcelData data, AnalysisContext context) {
                    String imgUrl = data.getImgUrlColumn();

                    if(isValidImageUrl(imgUrl)){
                        SdsMaterialTaskPic sdsMaterialTaskPic = new SdsMaterialTaskPic();
                        sdsMaterialTaskPic.setTaskId(taskId);  //任务id
                        sdsMaterialTaskPic.setPicUrl(imgUrl);
                        sdsMaterialTaskPic.setTitle("");  //导入中暂未生成标题,这边使用空字符串
                        sdsMaterialTaskPic.setAnalyseRes(0);   //分析结果设置为0  (进行中)
                        sdsMaterialTaskPic.setStatus(0);    //图片状态设置为0   分析中
                        sdsMaterialTaskPic.setUserId(userId);
                        sdsMaterialTaskPic.setOssUrl("");

                        list.add(sdsMaterialTaskPic);
                    }
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {
                    // 解析之后的回调
                    System.out.println("所有数据读取完毕!");
                    if (!list.isEmpty()){
                        materialTaskImportManager.saveBatch(list);
                        int num = list.size();
                        //更新导入状态
                        materialTaskService.updateTaskImportCondition(num, taskId);
                        //执行下载
                        materialTaskDownloadService.downloadImage(list, taskId);
                    }else {
                        //TODO 如果全部解析失败,列表为0,将状态直接更新为已完成
                        materialTaskService.updateTaskFailImportCondition(taskId);
                    }
                }
            })
                    .sheet()    //默认读取第一个sheet
                    .headRowNumber(1) //跳过第一行
                    .doRead();       // 开始读取

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //第一层过滤,判断url是否不是空行且符合后缀是.jpg或.png
    private boolean isValidImageUrl(String imgUrl){
        return imgUrl != null && !imgUrl.trim().isEmpty();

    }

}
